package cn.kgm.threadPool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 线程执行时是异步
 * 但是汇总数据时可以是同步的
 */
public class ThreadPoolStudy {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long l = System.currentTimeMillis();
        // 获取一个五个线程的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        List<Future<List<String>>> futures = new ArrayList<>();
        List<String> finalResult = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < 5; i++) {
            futures.add(executorService.submit(ThreadPoolStudy::fetchDataFromApi));
        }
        for (Future<List<String>> future : futures) {
            List<String> list = future.get();
            finalResult.addAll(list);
        }
        long x = System.currentTimeMillis();
        System.out.println(x - l);
        System.out.println(finalResult.size());
    }

    private static List<String> fetchDataFromApi() throws InterruptedException {
        Thread.sleep(200);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add(String.valueOf(i));
        }
        return list;
    }

}
